<template>
  <div class="chat-communication" ref="containerRef" id="chat-communications">
    <div class="chat-container">
      <div
        class="communication-box"
        v-show="messageList.length === 0 && !isLoading && !selectTopic.contextMsg"
      >
        <img class="box-avatar" :src="appConfigValue.bpaiAvatarUrl" alt="" />
        <div class="box-extra">
          <div class="box-message">
            <div class="message-title">
              {{ appConfigValue.initTitle }}
            </div>
          </div>
          <template v-if="topicArr && topicArr.length">
            <div class="extra-topic">
              <div class="topic-title">
                <img class="title-icon" :src="hotImg" alt="" />
                <div class="title-txt">今日热问</div>
                <!-- <template v-if="!sourceTagValue">
                  <div class="title-view" @click="viewMore">查看更多热点资讯>></div>
                </template> -->
              </div>
              <div class="topic-list">
                <div
                  class="topic-item"
                  v-for="(item, index) in topicArr"
                  :key="item.code"
                  @click="recommendHandle(item)"
                >
                  <div
                    class="topic-index"
                    :style="{ color: index > 2 ? '#E69E44' : '#d33b40' }"
                  >
                    {{ index + 1 }}
                  </div>
                  <a-tooltip placement="top">
                    <template #title>{{ item.content }}</template>
                    <div class="global-ellipsis">{{ item.content }}</div>
                  </a-tooltip>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div
        class="communication-box"
        v-if="messageList.length === 0 && selectTopic && selectTopic.contextMsg"
      >
        <img class="box-avatar" :src="appConfigValue.bpaiAvatarUrl" alt="" />
        <div class="box-extra">
          <div class="box-message">
            <div class="message-title">你好，这里是xxx 跟我聊聊吧~</div>
          </div>
        </div>
      </div>
      <div class="communication-box" v-if="selectTopic && selectTopic.contextMsg">
        <img class="box-avatar" :src="appConfigValue.bpaiAvatarUrl" alt="" />
        <div class="box-extra">
          <div class="box-message">
            <div class="message-content" v-html="contextMsgFormat(selectTopic)"></div>
          </div>
        </div>
      </div>
      <!-- <VueEternalLoading
        :load="infiniteHandler"
        position="top"
        :container="containerRef"
        v-model:is-initial="isInitial"
      >
        <template #loading>
          <div class="eternal-loading">
            <loading-outlined class="loading-icon" />
            <div class="loading-txt">数据加载中</div>
          </div>
        </template>
        <template #no-more>
          <div class="eternal-more"></div>
        </template>
      </VueEternalLoading> -->
      <div
        :class="[
          'communication-box',
          item.direction === 'Q' ? 'communication-question' : '',
        ]"
        v-for="(item, index) in messageList"
        :key="index"
      >
        <template v-if="item.direction !== 'Q'">
          <img class="box-avatar" :src="appConfigValue.bpaiAvatarUrl" alt="" />
        </template>
        <div class="box-extra">
          <div
            :class="[
              'box-message',
              item.responseStatus === 'waitLoading' && !item.contextMsg
                ? 'message-loading'
                : '',
            ]"
          >
            <!-- 文字 -->
            <div
              class="box-stop"
              v-if="item.responseStatus === 'waitLoading' && !item.contextMsg"
            >
              <div class="message-loading">
                <div class="loading-dot"></div>
                <div class="loading-dot"></div>
                <div class="loading-dot"></div>
              </div>
            </div>

            <div class="message-content" v-else v-html="contextMsgFormat(item)"></div>
          </div>
          <!-- 操作 -->
          <div
            class="extra-handle"
            v-if="item.direction !== 'Q' && item.responseStatus !== 'waitLoading'"
          >
            <div class="handle-source" v-if="item.source && item.source.length">
              <div class="source-btn" @click="expandSource(item)">
                参考来源
                <down-outlined class="btn-icon" :rotate="item.expand ? 0 : 180" />
              </div>
            </div>
          </div>
          <div
            class="extra-source"
            v-if="
              item.direction !== 'Q' &&
              item.responseStatus !== 'waitLoading' &&
              item.source &&
              item.source.length &&
              !item.expand
            "
          >
            <div
              class="source-item"
              v-for="(sourceItem, index) in item.source"
              :key="index"
              @click="openNewPage(sourceItem.seeMoreUrl)"
            >
              <a-tooltip placement="top">
                <template #title>{{ limitTitle(sourceItem.title) }}</template>
                <div class="item-title global-ellipsis">{{ sourceItem.title }}</div>
              </a-tooltip>

              <div class="item-name">
                <img
                  v-if="sourceItem.image"
                  class="name-img"
                  :src="sourceItem.image"
                  alt=""
                />
                <div v-else class="name-img"></div>
                <div class="name-txt global-ellipsis">{{ sourceItem.showName }}</div>
              </div>
            </div>
          </div>
          <!-- 推荐问题 -->
          <div class="extra-recommend" v-if="recommendShow(item, index)">
            <div class="recommend-info">
              已帮您联想到以下问题，可以点击下方问题继续提问：
            </div>
            <div
              class="recommend-title global-ellipsis"
              v-for="recommendItem in item.recommend"
              :key="recommendItem.recommendNo"
              @click="recommendHandle(recommendItem)"
            >
              {{ recommendItem.content }}
            </div>
          </div>
        </div>

        <template v-if="item.direction === 'Q'">
          <img class="box-avatar" :src="appConfigValue.userAvatarUrl" alt="" />
        </template>
      </div>
      <div id="scrollBox"></div>
    </div>
    <!-- <TopicModal @register="topicRegister" @msgHandle="msgHandle"></TopicModal> -->
  </div>
</template>

<script setup>
// import IconFont from "@/components/IconFont/index.vue";
import { DownOutlined, LoadingOutlined } from "@ant-design/icons-vue";
// import { formatToAfterTime } from "@/utils/dateUtil";
import { message } from "ant-design-vue";
import { md } from "../chat";
// import useClipboard from "vue-clipboard3";
// import { bpaiData } from "@/utils/constantMap";
// import TopicModal from "@/views/chat/components/TopicModal.vue";
// import { useModal } from "@/components/Modal";
// import { useGoPage } from "@/hooks/useGoPage";

import { useChatData } from "../hooks/useChatData";
// import { userStore } from "@/store/modules/user";
import { VueEternalLoading } from "@ts-pro/vue-eternal-loading";

import bpaiAvatarImg from "@/assets/images/chat/bpaiAvatar.png";
import userAvatarImg from "@/assets/images/chat/userAvatar.png";
import hotImg from "@/assets/images/chat/hot.png";

// import { queryPageMsg } from "@/api";
import { useAppStore } from "@/store/modules/app.js";

const appStore = useAppStore();


// const { toClipboard } = useClipboard();
const { selectSessionId } = useChatData();
// const userModule = userStore();
// const goPage = useGoPage();

// const [topicRegister, { openModal }] = useModal();

const emit = defineEmits(["addMessage", "sendMessage", "msgHandle"]);

const props = defineProps({
  messageList: {
    type: Array,
    default: () => [],
  },
  selectTopic: {
    type: Object,
    default: () => {},
  },
});

const isNewMessage = ref(true);
const isInitial = ref(true);
const isLoading = ref(false);
const containerRef = ref();
const topicArr = ref([]);

// const tokenValue = computed(() => userModule.token);
const appConfigValue = computed(() => appStore.appConfigValue);

// const sourceTagValue = computed(() => userModule.sourceTag === "1");
onMounted(() => {
  initGetTopTopic();
});
const initGetTopTopic = async () => {
  // let res = await getTopTopic();
  let arr = [
    "如何处理 VTE 系统中用户不存在的问题？",
    "用户忘记密码应该如何在 VTE 系统中重置密码？",
    "如何为 VTE 系统中的用户添加科室/病区的权限？",
    "患者360是什么？",
    // "VTE 系统如何帮助医生进行风险评估？",
    "VTE 防控系统有哪些功能？",
    "如何确保 VTE 防控措施的有效性？",
    "VTE 安装运行时被其他系统阻止了怎么办？",
    "如何解决 VTE 评估时提示安装文件被损坏的问题？",
    "当进行患者评分时系统提示未配置评估方案应该如何处理？",
  ];
  const shuffled = arr
    .map((value, index) => ({ content: value, code: index }))
    .sort(() => 0.5 - Math.random());
  topicArr.value = shuffled.slice(0, 3);
};

const initInfinite = () => {
  isInitial.value = true;
};
const msgHandle = (params) => {
  emit("msgHandle", params);
};
// const viewMore = () => {
//   goPage("/information");
// };
// const infiniteHandler = async ({ loaded, noMore }) => {
//   isLoading.value = true;
//   // if (!selectSessionId.value) {
//   //   initGetTopTopic();
//   // }
//   if (!selectSessionId.value) {
//     isNewMessage.value = true;
//     noMore();
//     isLoading.value = false;
//     return;
//   }
//   isNewMessage.value = false;
//   try {
//     let pageSize = 10;
//     let endTime =
//       props.messageList && props.messageList.length
//         ? props.messageList[0].recordTime
//         : "";
//     let { result } = await queryPageMsg({
//       pageNum: 1,
//       pageSize,
//       endTime,
//       sessionId: selectSessionId.value,
//     });
//     let list = result.list;
//     if (list && list.length) {
//       list = list.map((item) => {
//         let recordContent = {};
//         if (item.recordContent) {
//           recordContent = JSON.parse(item.recordContent);
//         }
//         return { ...recordContent, ...item, recommend: [] };
//       });
//       list = list.reverse();
//       emit("addMessage", list);
//       if (list.length < pageSize) {
//         noMore();
//       } else {
//         loaded();
//       }
//     } else {
//       noMore();
//     }
//     isLoading.value = false;
//   } catch (err) {
//     noMore();
//     isLoading.value = false;
//   }
// };
// 对话markdown格式化
const contextMsgFormat = (item) => {
  let contextMsg = item.contextMsg;
  if (contextMsg) {
    contextMsg = contextMsg.replace(/\\n/g, "\r\n"); // 转化标题
    if (item.direction === "A" && item.responseStatus === "waitLoading") {
      contextMsg = contextMsg + '  <span class="cursor-blink"></span>';
    }
    if (item.direction === "A" && item.responseStatus !== "waitLoading") {
      if (item.extField) {
        let extField = JSON.parse(item.extField);
        if (extField.stopSend == "1") {
          contextMsg = contextMsg + `<div class='msg-stop'><span>用户已停止</span></div>`;
        }
      }
      // contextMsg = formatLawCase(contextMsg)
    }
    contextMsg = md.render(contextMsg);
  }
  return contextMsg;
};

// 格式化法条和案例
// const formatLawCase = (contextMsgStr) => {
//   let contextMsg = contextMsgStr;
//   let relatedLaws = "### 相关法条";
//   let relatedCase = "### 相关案例";

//   if (contextMsg.includes(relatedLaws)) {
//     let lawSection = contextMsg.split(relatedLaws)[1].split("###")[0].trim();
//     let laws = lawSection.split("\r\n");
//     if (laws.length) {
//       const regex = /(.*?)第([一二三四五六七八九十百千万亿零\d]+)条(.*)/;
//       for (let i in laws) {
//         let match = laws[i].match(regex);
//         if (match && match.length) {
//           let noHeaderStr = match[1].replace("- ", "");
//           laws[
//             i
//           ] = `- <span class="law-cursor">${noHeaderStr}第${match[2]}条</span>${match[3]}`;
//         }
//       }
//     }
//     contextMsg =
//       contextMsg.split(relatedLaws)[0] +
//       relatedLaws +
//       "\r\n" +
//       laws.join("\r\n") +
//       "\r\n###" +
//       contextMsg.split(relatedLaws)[1].split("###")[1];
//   }

//   if (contextMsg.includes(relatedCase)) {
//     let caseList = contextMsg.split(relatedCase)[1].trim().split("\r\n");
//     console.info(caseList);
//     if (caseList.length) {
//       const caseRegex = /(.*?)号(.*)/;
//       for (let i in caseList) {
//         let match = caseList[i].match(caseRegex);
//         if (match && match.length && match[1].includes("（") && match[1].includes("）")) {
//           let noCaseHeaderStr = match[1].replace("- ", "");
//           caseList[
//             i
//           ] = `- <span class="law-cursor">${noCaseHeaderStr}号</span>${match[2]}`;
//         }
//       }
//     }
//     contextMsg =
//       contextMsg.split(relatedCase)[0] + relatedCase + "\r\n" + caseList.join("\r\n");
//   }
//   return contextMsg;
// };
// 复制文案
// const handleCopyLink = async (contextMsg) => {
//   let copyMsg = contextMsg.replace(/\\n/g, "\r\n");
//   await toClipboard(copyMsg);
//   message.success("文本复制成功");
// };
// 点赞/踩
// const operateAction = async (item, statusType) => {
//   // if (!tokenValue.value && !sourceTagValue.value) {
//   //   userModule.setLoginModel('1')
//   //   userModule.setVisitorsMsg({})
//   //   return
//   // }
//   let status = statusType;
//   if (item.likeStatus === "good" && status === "good") {
//     status = "unGood";
//   } else if (item.likeStatus === "bad" && status === "bad") {
//     status = "unBad";
//   }
//   await msgLike({
//     sessionId: item.sessionId,
//     msgId: item.msgId,
//     status,
//   });
//   item.likeStatus = status;
// };
const expandSource = (item) => {
  item.expand = !item.expand;
};

// 标题长度限制
const limitTitle = (title) => {
  if (title && title.length > 45) {
    return title.substring(0, 45) + "...";
  } else {
    return title;
  }
};
// 打开新页面
const openNewPage = (url) => {
  if (url) {
    window.open(url, "_blank");
  } else {
    message.warning("来源地址为空");
  }
};
// 推荐问题显示
const recommendShow = (item, index) => {
  return (
    item.direction !== "Q" &&
    item.responseStatus !== "waitLoading" &&
    item.recommend &&
    item.recommend.length &&
    index === props.messageList.length - 1
  );
};
const recommendHandle = (item) => {
  let sendMsg = {
    // direction: "Q",
    // contextMsg: item.content,
    // recommendNo: item.recommendNo,
    // // ...bpaiData,
    // chatType: "chat",
    // model: "Premium_Version",
    // terminalType: "web",

    direction: "Q",
    contextMsg: item.content,
    chatType: "chat",
    modelOptions: "demo",
    terminalType: "web",
    historyDialogue: [],
  };
  emit("sendMessage", sendMsg);
};
const sendTopic = (item) => {
  openModal(true, item);
};
// 滚动
const scrollHandle = () => {
  nextTick(() => {
    const $container = document.getElementById("chat-communications");
    if ($container) {
      setTimeout(() => {
        $container.scrollTop = $container.scrollHeight;
      }, 400);
    }
  });
};
defineExpose({
  scrollHandle,
  initInfinite,
});
</script>

<style lang="scss" scoped>
$primary-set-color: #2a64f6;
$primary-gradient-color: linear-gradient(135deg, #5594ff 0%, #002cff 100%);
$primary-hover-color: #548aff;
$primary-disabled-color: #89bbf9;

.chat-communication {
  width: 100%;
  flex: 1;
  overflow-y: auto;
  display: flex;
  justify-content: center;
  .chat-container {
    width: 100%;
    min-width: 600px;
    max-width: 964px;
    padding: 40px 48px 0;
  }
  .eternal-loading {
    margin: 8px 0;
    .loading-icon {
      color: $primary-set-color;
      font-size: 20px;
      margin: 0 auto;
      display: block;
    }
    .loading-txt {
      color: $primary-set-color;
      font-size: 12px;
      margin-top: 8px;
      text-align: center;
    }
  }
  .eternal-more {
    font-size: 14px;
    color: #c0c0c0;
    text-align: center;
  }
  .communication-box {
    margin-bottom: 16px;
    display: flex;
    .box-avatar {
      margin-right: 8px;
      flex-shrink: 0;
      // border: 1px solid #e0e1e6;
      border-radius: 50%;
      width: 28px;
      height: 28px;
      box-sizing: border-box;
    }
    .box-extra {
      max-width: calc(100% - 72px);
      display: flex;
      flex-direction: column;
      align-items: flex-start;
    }
    .extra-message {
      font-size: 12px;
      line-height: 22px;
      color: $primary-set-color;
      cursor: pointer;
    }
    .extra-handle {
      margin-top: 4px;
      padding-right: 4px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      .handle-source {
        margin-right: 16px;
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        .source-btn {
          height: 18px;
          line-height: 18px;
          border-radius: 9px;
          padding: 0 16px;
          font-size: 12px;
          color: #c0c0c0;
          background-color: #fff;
          display: flex;
          align-items: center;
          cursor: pointer;
          .btn-icon {
            color: #565c6e;
            font-size: 14px;
            font-weight: bold;
            margin-left: 8px;
          }
        }
      }
      .handle-operate {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .operate-line {
          width: 1px;
          height: 12px;
          margin: 1px 8px;
          background: #e0e1e6;
        }
        .operate-icon {
          font-weight: bold;
          color: #555d6f;
          font-size: 12px;
          cursor: pointer;
          &:hover {
            color: $primary-set-color;
          }
          &.icon-active {
            color: $primary-set-color;
          }
        }
      }
    }
    .extra-source {
      margin-top: 4px;
      display: flex;
      flex-wrap: wrap;
      .source-item {
        width: 188px;
        height: 74px;
        margin: 0 4px 4px 0;
        padding: 0 16px;
        background: #e9ebf3;
        border-radius: 16px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        cursor: pointer;
        overflow: hidden;
        .item-title {
          color: $primary-set-color;
          font-size: 12px;
          line-height: 20px;
          margin-bottom: 4px;
          cursor: pointer;
        }
        .item-name {
          display: flex;
          align-items: center;
          .name-img {
            flex-shrink: 0;
            width: 16px;
            height: 16px;
            background: #f3f4f8;
            border-radius: 22px;
            margin-right: 4px;
          }
          .name-txt {
            font-weight: 600;
            font-size: 12px;
          }
        }
      }
    }
    .extra-recommend {
      margin-top: 16px;
      display: flex;
      // flex-wrap: wrap;
      flex-direction: column;
      align-items: flex-start;
      .recommend-info {
        margin-left: 8px;
        margin-bottom: 8px;
        color: #565c6e;
        font-weight: 600;
        font-size: 12px;
      }
      .recommend-title {
        max-width: 420px;
        margin-right: 4px;
        margin-bottom: 4px;
        padding: 6px 8px;
        line-height: 20px;
        color: #192236;
        font-size: 12px;
        border-radius: 8px;
        background: #ffffff;
        cursor: pointer;
        &:hover {
          background: $primary-hover-color;
        }
      }
    }
    .extra-topic {
      width: 100%;
      .topic-title {
        height: 32px;
        margin: 4px 0 4px 8px;
        display: flex;
        align-items: center;
        .title-icon {
          width: 16px;
          height: 16px;
        }
        .title-txt {
          margin-left: 5px;
          font-size: 12px;
          color: #192236;
          font-weight: bold;
          margin-top: 2px;
        }
        .title-view {
          color: $primary-set-color;
          margin-left: 16px;
          margin-top: 2px;
          font-size: 12px;
          cursor: pointer;
        }
      }
      .topic-list {
        display: flex;
        flex-wrap: wrap;
        .topic-item {
          max-width: 100%;
          margin-right: 4px;
          margin-bottom: 4px;
          padding: 5px 16px;
          line-height: 22px;
          color: #192236;
          font-size: 12px;
          border-radius: 8px;
          background: #ffffff;
          display: flex;
          align-items: center;
          cursor: pointer;
          &:hover {
            background: $primary-hover-color;
          }
          .topic-index {
            flex-shrink: 0;
            font-size: 12px;
            font-weight: bold;
            margin-right: 16px;
          }
        }
      }
    }
    .box-message {
      padding: 12px 16px;
      background-color: #fff;
      border-radius: 0 8px 8px 8px;
      color: #192236;
      line-height: 24px;
      font-size: 14px;
      &.message-loading {
        background-color: transparent;
        padding: 0;
      }
      .message-title {
        font-weight: bold;
      }
      :deep(.message-content) {
        word-break: break-all;
        .cursor-blink {
          display: inline-block;
          width: 4px;
          height: 12px;
          position: relative;
          font-weight: 600;
          animation: blink-animation 1s linear infinite;
          &::after {
            content: "";
            position: absolute;
            width: 1px;
            height: 15px;
            background-color: #192236;
            left: 0;
            top: 0;
          }
        }
        .law-cursor {
          cursor: pointer;
          color: $primary-set-color;
        }
        @keyframes blink-animation {
          0% {
            opacity: 1;
          }
          50% {
            opacity: 0;
          }
          100% {
            opacity: 1;
          }
        }
        p,
        table,
        li,
        h1,
        h2,
        h3,
        h4,
        h5,
        h6 {
          margin-bottom: 12px;
          font-size: 14px;
          font-weight: 600;
        }
        p,
        table,
        li {
          font-weight: 400;
        }
        ul {
          padding-left: 32px;
          list-style-type: circle;
        }
        ol {
          list-style: decimal;
          padding-left: 32px;
        }
        li {
          margin-bottom: 6px;
        }
        p:last-child {
          margin-bottom: 0;
        }
        code,
        pre {
          white-space: pre-wrap;
          word-wrap: break-word;
        }
        table {
          overflow-x: auto;
          th {
            word-break: keep-all;
            word-wrap: break-word;
          }
          th,
          td {
            padding: 2px 6px;
          }
        }
        .msg-stop {
          display: flex;
          justify-content: flex-end;
          span {
            width: 75px;
            height: 18px;
            line-height: 18px;
            background: #f3f4f8;
            border-radius: 22px;
            color: #c0c0c0;
            text-align: center;
            font-size: 12px;
          }
        }
      }
      .message-operate {
        margin-top: 8px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .operate-buy {
          font-weight: 700;
          font-size: 12px;
          color: #ffffff;
          text-align: center;
          width: 56px;
          height: 32px;
          line-height: 32px;
          background: $primary-gradient-color;
          border-radius: 4px;
          cursor: pointer;
        }
        .operate-share {
          width: 56px;
          height: 32px;
          border-radius: 4px;
          border: 1px solid $primary-set-color;
          margin-left: 8px;
          font-weight: 700;
          font-size: 12px;
          color: $primary-set-color;
          line-height: 32px;
          text-align: center;
          cursor: pointer;
        }
      }
    }
    .box-stop {
      .message-loading {
        padding: 15px 8px;
        background-color: $primary-disabled-color;
        border-radius: 0 8px 8px 8px;
        color: #fff;
        display: flex;
        align-items: center;

        .loading-dot {
          background-color: #fff;
          width: 6px;
          height: 6px;
          border-radius: 100%;
          margin: 0 2px;
          animation-fill-mode: both;
          @keyframes scale {
            0% {
              transform: scale(1);
              opacity: 1;
            }

            45% {
              transform: scale(0.1);
              opacity: 0.7;
            }

            80% {
              transform: scale(1);
              opacity: 1;
            }
          }
          &:nth-child(1) {
            animation: scale 1s 0.12s infinite cubic-bezier(0.2, 0.68, 0.18, 1.08);
          }
          &:nth-child(2) {
            animation: scale 1s 0.24s infinite cubic-bezier(0.2, 0.68, 0.18, 1.08);
          }
          &:nth-child(3) {
            animation: scale 1s 0.36s infinite cubic-bezier(0.2, 0.68, 0.18, 1.08);
          }
        }
      }
      .message-stop {
        font-size: 12px;
        color: $primary-set-color;
        line-height: 22px;
        cursor: pointer;
      }
    }
    &.communication-question {
      justify-content: flex-end;
      .box-extra {
        align-items: flex-end;
      }
      .box-avatar {
        margin-left: 8px;
        margin-right: 0;
      }
      .box-message {
        background-color: $primary-set-color;
        color: #fff;
        border-radius: 8px 0 8px 8px;
        :deep(.message-content) {
          a {
            color: #00ffff;
          }
          p,
          li,
          h1,
          h2,
          h3,
          h4,
          h5,
          h6 {
            margin-bottom: 0;
            font-weight: 400;
          }
        }
      }
    }
  }
}
</style>
